package com.yuanduan.mplus.view;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cj.framework.util.HttpImp;
import com.cj.framework.util.IHttp;
import com.cj.framework.util.RSAUtils;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.model.DBManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by cj on 2016/6/16.
 * Email:781806481@qq.com
 * 废弃
 */
public class ReportFragment_1 extends Fragment implements RadioGroup.OnCheckedChangeListener {
    private LineChart lineChart;
    private RadioGroup rg;
    private TextView tv_1;
    private TextView tv_2;
    private ArrayList<SafetyDriveDetailActivity.DateInfo> dateInfos;

    private List<String> legendTitleList;
    private List<String> xValues;
    private ArrayList<ArrayList<Float>> datas=new ArrayList<ArrayList<Float>>();

    private ProgressDialog progressDialog;
    private IHttp iHttp=new HttpImp();
    private IHttp.HttpInfoCallbackWithIndex callback=new IHttp.HttpInfoCallbackWithIndex() {
        @Override
        public void onSucceed(Object result, int index) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                }
            },500);
            String result1= RSAUtils.decryptWithRSA((String) result);
            JSONObject jsonObject=null;
            try {
                jsonObject=new JSONObject(result1);
                if(jsonObject==null){
                    return;
                }
                if(jsonObject.getInt("RS")!=1){
                    return;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            switch (index){
                case 0:
                    fillData(jsonObject);
                    animalLineChart(legendTitleList,xValues);
                    break;
                case 1:
                    fillData(jsonObject);
                    animalLineChart(legendTitleList,xValues);
                    break;
                case 2:
                    fillData(jsonObject);
                    animalLineChart(legendTitleList,xValues);
                    break;
                case 3:
                    fillData(jsonObject);
                    animalLineChart(legendTitleList,xValues);
                    break;
            }
        }

        @Override
        public void onFailed(Object result, int index) {

        }
    };

    private void animalLineChart(List<String> legendTitleList,List<String> xValues) {
        List<ILineDataSet> lists=new ArrayList<ILineDataSet>();
        for(int i = 0; i< datas.size(); i++){
            int hh= datas.size();
            int jj= datas.get(i).size();
            List<Entry> entryList=new ArrayList<Entry>();
            for(int j = 0; j< datas.get(i).size(); j++){
                Entry entry=new Entry(datas.get(i).get(j),j);
                entryList.add(entry);
            }
            LineDataSet sets=new LineDataSet(entryList,legendTitleList.get(i));
            lists.add(sets);
        }
        ((LineDataSet)lists.get(0)).setColor(getResources().getColor(android.R.color.holo_red_light));
        ((LineDataSet)lists.get(0)).setCircleColor(getResources().getColor(android.R.color.holo_red_light));
        ((LineDataSet)lists.get(0)).setDrawCircleHole(false);
        ((LineDataSet)lists.get(1)).setColor(getResources().getColor(android.R.color.holo_blue_light));
        ((LineDataSet)lists.get(1)).setCircleColor(getResources().getColor(android.R.color.holo_blue_light));
        ((LineDataSet)lists.get(1)).setDrawCircleHole(false);
        LineData lineData=new LineData(xValues,lists);
        lineChart.setData(lineData);
        lineChart.animateY(2000, Easing.EasingOption.EaseInCubic);
    }

    private void fillData(JSONObject result) {
        datas.clear();
        xValues.clear();
        ArrayList<Float> selfdata=new ArrayList<Float>();
        ArrayList<Float> mindata=new ArrayList<Float>();
        ArrayList<Float> maxdata=new ArrayList<Float>();
        try {
            JSONArray jsonArray=result.getJSONArray("Data");
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                selfdata.add((float) jsonObject.getInt("self"));
                mindata.add((float) jsonObject.getInt("minimum"));
                maxdata.add((float) jsonObject.getInt("max"));
                xValues.add(jsonObject.getInt("Week")+"");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        datas.add(maxdata);
        datas.add(selfdata);
        datas.add(mindata);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dateInfos=SafetyDriveDetailActivity.getDateInfos();
        progressDialog=new ProgressDialog(getContext());
        legendTitleList=new ArrayList<String>();
        xValues=new ArrayList<String>();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_report1,null);
        lineChart= (LineChart) view.findViewById(R.id.lineChart);
        rg= (RadioGroup) view.findViewById(R.id.report_rg);
        ((RadioButton)rg.getChildAt(0)).setText(dateInfos.get(0).weekcode+"周(上周)");
        ((RadioButton)rg.getChildAt(1)).setText(dateInfos.get(1).weekcode+"周");
        ((RadioButton)rg.getChildAt(2)).setText(dateInfos.get(2).weekcode+"周");
        ((RadioButton)rg.getChildAt(3)).setText(dateInfos.get(3).weekcode+"周");
        tv_1= (TextView) view.findViewById(R.id.report_tv_1);
        tv_1.setText(dateInfos.get(0).weekcode+"周"+((ReportActivity)getActivity()).Type+"趋势分析");
        tv_2= (TextView) view.findViewById(R.id.report_tv_2);
        init();
        return view;
    }

    private void init(){
        legendTitleList.add("MAX("+((ReportActivity)getActivity()).reportType+")");
        legendTitleList.add(((ReportActivity) getActivity()).reportType);
        legendTitleList.add("AVG("+((ReportActivity)getActivity()).reportType+")");

        //设置折线图
        lineChart.setDescription("");
        lineChart.setNoDataText("暂无数据");
        YAxis yAxis=lineChart.getAxisLeft();
        yAxis.setLabelCount(8,true);
        yAxis.setAxisMinValue(0);
        yAxis.setDrawGridLines(false);
        lineChart.getAxisRight().setDrawGridLines(false);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getLegend().setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        lineChart.getXAxis().setDrawGridLines(false);

        rg.setOnCheckedChangeListener(this);
        rg.check(R.id.report_rb_zhou1);
        progressDialog.show();
        iHttp.httpInfoPostWithIndex(Config.URL,new HashMap<String, String>(),callback,0);
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        HashMap<String,String> hashMap=new HashMap<>();
        if(Config.userType==2){
            hashMap.put("UserPhone",getActivity().getIntent().getExtras().getString("UserPhone"));
        }else if(Config.userType==1){
            hashMap.put("UserPhone", DBManager.getInstance(getActivity().getApplicationContext()).getUser().getUserPhone());
        }
        hashMap.put("Type",((ReportActivity)getActivity()).Choose);
        hashMap.put("AttributeName",((ReportActivity) getActivity()).Type);
        switch (checkedId){
            case R.id.report_rb_zhou1:
                tv_1.setText(dateInfos.get(0).weekcode+"周"+((ReportActivity)getActivity()).Type+"趋势分析");
                hashMap.put("YearCode",dateInfos.get(0).yearcode+"");
                hashMap.put("WeekCode",dateInfos.get(0).weekcode+"");
                progressDialog.show();
                iHttp.httpInfoPostWithIndex(Config.URL+Config.ATTRIBUTEDETAIL,Config.translateMap(hashMap),callback,0);
                break;
            case R.id.report_rb_zhou2:
                tv_1.setText(dateInfos.get(1).weekcode+"周"+((ReportActivity)getActivity()).Type+"趋势分析");
                hashMap.put("YearCode",dateInfos.get(1).yearcode+"");
                hashMap.put("WeekCode",dateInfos.get(1).weekcode+"");
                progressDialog.show();
                iHttp.httpInfoPostWithIndex(Config.URL+Config.ATTRIBUTEDETAIL,Config.translateMap(hashMap),callback,1);
                break;
            case R.id.report_rb_zhou3:
                tv_1.setText(dateInfos.get(2).weekcode+"周"+((ReportActivity)getActivity()).Type+"趋势分析");
                hashMap.put("YearCode",dateInfos.get(2).yearcode+"");
                hashMap.put("WeekCode",dateInfos.get(2).weekcode+"");
                progressDialog.show();
                iHttp.httpInfoPostWithIndex(Config.URL+Config.ATTRIBUTEDETAIL,Config.translateMap(hashMap),callback,2);
                break;
            case R.id.report_rb_zhou4:
                tv_1.setText(dateInfos.get(3).weekcode+"周"+((ReportActivity)getActivity()).Type+"趋势分析");
                hashMap.put("YearCode",dateInfos.get(3).yearcode+"");
                hashMap.put("WeekCode",dateInfos.get(3).weekcode+"");
                progressDialog.show();
                iHttp.httpInfoPostWithIndex(Config.URL+Config.ATTRIBUTEDETAIL,Config.translateMap(hashMap),callback,3);
                break;
        }
    }
}
